<?php
require_once('TVB/VideoInfrastructure/Client/requires.php');
require_once('TVB/ImageInfrastructure/Client/requires.php');

class P_VideoGetAction extends BaseAction 
{
	public $id;
	public $act;
	public $from;
	public $unpublish;
	public $error_code;
	public $tag;
    public $ut;
    public $deleted_chapters;

    private $_programme_premium_flag;

	public function execute()
	{
		if(!is_null($this->error_code))
		{
			$this->addError('Video.Edit', array($this->error_code, 'Video.Edit'));
		}

		try{
			# add publish log
			$this->setData("publishLog", publish_log::getPublishLog('video', $this->id));
            $this->setData('special_operation_premium', TRUE);

			if(!empty($this->unpublish)) {Model::$dbo['r'] = CommonUtils::getDbConn(0,'preview');}
            //allow tags
            $chapter_allow_tag = CommonUtils::get_allow_tags("chapter");
           

			# set tags field
			$video_allow_tag = CommonUtils::get_allow_tags("video");
			$tag_type  = new tag_type();
			$allow_tag_list = $tag_type->findByInSql($video_allow_tag);
			$tag_arr = array();
			$all_tag_list = array();
			foreach ($allow_tag_list as $tag)
			{
				$tag_arr[$tag->id] = array("id"=>$tag->id,"name"=>$tag->system_label,'restrict'=>$tag->restricted);
				$all_tag_list[$tag->id] = array();
			}
			$this->setData("video_allow_tag",$tag_arr);

			# video getDetails
			$video          =   new p_video();
			$country        =   new country();
        	$en_langid = language::getLanguageID(AC::LANGUAGE_EN);
		    $zh_langid = language::getLanguageID(AC::LANGUAGE_ZH);
	
			if($this->act == 'add'){
				$video_detail = array(
					'tags' => '',
					'programme'=>'',
					'programme_id'=>'',
					'programme_title_cn'=>'',
					'programme_title_en'=>'',
					'programme_path'=>'',
					'title'=>'',
                    'video_language'=>array($zh_langid=>array('title'=>'','description'=>''),$en_langid=>array('title'=>'','description'=>'')),
					'description'=>'',
					'image_source_url'=>AC::PDES_FLASH_ASSETS_PROCESS,
					'source_url'=>AC::PDES_FLASH_ASSETS_PROCESS,
					'country_deny_list'=>'',
					'country_allow_list'=>'ALL',
					'status'=>AC::VIDEO_STATUS_QUEUE,
					'first_time_onair' => array('',''),
					'publish_datetime' => array('',''),
					'expire_datetime' => array('',''),
					'video_type' => 'O',
				);
				$this->setData("onair_episode_no",'');

			}else{
				$video_detail                   =   $video->getDetails((int)$this->id);
                $this->initProgrammePremiumFlag($video_detail['programme_id']);
                //$video_detail['premium_flag'] = $this->_programme_premium_flag;
                $video_detail['premium_flag'] = isset($video_detail['premium_flag']) ? $video_detail['premium_flag'] : 0;
				$video_detail['first_time_onair']   =   CommonUtils::formatDate($video_detail['first_time_onair']);
				$video_detail['publish_datetime']   =   CommonUtils::formatDate($video_detail['publish_datetime']);
				$video_detail['expire_datetime']    =   CommonUtils::formatDate($video_detail['expire_datetime']);
                $video_detail['mdes_status'] = empty($video_detail['mdes_status']) ? '1' : $video_detail['mdes_status'] ;
                $premium = $this->__init_video_premium();
                $video_detail['subscription_flag'] = isset($premium->subscription_flag) ? $premium->subscription_flag  : 0;
                $video_detail['ppv_flag'] = isset($premium->ppv_flag) ? $premium->ppv_flag : 0;
                $video_detail['video_type'] = isset($video_detail['video_type']) ? strtoupper($video_detail['video_type']): 'O';

                $this->__init_video_subscription();
                $this->__init_video_ppv();

                if('ALL' == $video_detail['country_allow_list'])
                {
                    $deny_flag = 1; 
                    $g_country = $video_detail['country_deny_list'];
                }
                else
                {
                    $deny_flag = 0;
                    $g_country = $video_detail['country_allow_list'];
                }
                $video_detail['global_country'] = $g_country;
                $video_detail['global_country_allow_deny'] = $deny_flag;

                if ($video_detail['video_params']) {
                    $json_param = json_decode($video_detail['video_params']);
                    $vi_client = new VideoInfrastructureClient();
				    $video_detail['download_url'] = $vi_client->getExportVideoUrlEasily($json_param->export_id);
                } else {
                    $video_detail['download_url'] = '';
                }

                if ($video_detail['ii_id']) {
                    $img_client = new ImageInfrastructureClient();
                    $video_detail['thumbnail_source_url'] = $img_client->GetSourceImageUrl($video_detail['ii_id']);
                }

				switch($video_detail['vi_status']){
				case AC::VIDEO_STATUS_QUEUE:
					$video_detail['source_url'] = AC::PDES_FLASH_ASSETS_PROCESS;
					$video_detail['image_source_url'] = AC::PDES_FLASH_ASSETS_PROCESS;
					break;
				case AC::VIDEO_STATUS_WAITING:
					$video_detail['source_url'] = AC::PDES_FLASH_ASSETS_WAIT;
					$video_detail['image_source_url'] = AC::PDES_FLASH_ASSETS_WAIT;
					break;
				case AC::VIDEO_STATUS_FAILED:
					$video_detail['source_url'] = AC::PDES_FLASH_ASSETS_FAILURE;
					$video_detail['image_source_url'] = AC::PDES_FLASH_ASSETS_FAILURE;
					break;
				}

				# get episode onair_episode_no if video in episode-video table
				$en = language::getLanguageID(AC::LANGUAGE_EN);
				$zh = language::getLanguageID(AC::LANGUAGE_ZH);
				$sql_eid = "
					select 
						e.onair_episode_no,e.id,
						(select description from `p_episode-language` where episode_id=e.id and language_id=$en) as en,
						(select description from `p_episode-language` where episode_id=e.id and language_id=$zh) as zh
					from 
                    `p_episode` e left join `p_episode-video` ev on e.id=ev.episode_id 
                    where ev.video_id = :vid";
				$data = Model::selectBySql($sql_eid,array(':vid'=>$this->id));
				$this->setData("exist_onair_episode_no", isset($data[0]) ? $data[0]['onair_episode_no'] : '');
			    $this->setData("onair_episode_no", isset($data[0]) ? $data[0]['onair_episode_no'] : '');
			    $this->setData("episode_id", isset($data[0]) ? $data[0]['id'] : '');
				$this->setData("week_en_encode", isset($data[0]['en']) ? $data[0]['en'] : '');
				$this->setData("week_zh_encode", isset($data[0]['zh']) ? $data[0]['zh'] : '');
				$this->setData("id", $this->id);
                $this->setData('eps',p_episode::getEpisodeNumByProgrammeId($video_detail['programme_id']));
			}
			$video_detail['countryList'] = $country->getCountryList();
            $this->initCountry();

            //$this->initVideoSubscription();
            $en_langid = language::getLanguageID(AC::LANGUAGE_EN);
            $zh_langid = language::getLanguageID(AC::LANGUAGE_ZH);
            $subtitle_cn = isset($video_detail['video_language'][$zh_langid]['subtitle']) ? $video_detail['video_language'][$zh_langid]['subtitle'] : '';
            $subtitle_en = isset($video_detail['video_language'][$en_langid]['subtitle']) ? $video_detail['video_language'][$en_langid]['subtitle'] : '';
            $video_detail['subtitle_cn']= $subtitle_cn;
            $video_detail['subtitle_en']= $subtitle_en;

            if($this->tag){
                $video_detail['tags']        = $this->tag;//get_tags();
            }

            if($video_detail['tags']){
				$tag_obj = new p_tag();
				$tag_list = $tag_obj->getTagList($video_detail['tags']);
				foreach($tag_list as $tag){
                  	$all_tag_list[$tag->typeid][] = array('id'=>$tag->id, 'system_label'=>htmlentities($tag->system_label, ENT_QUOTES, 'UTF-8'));
				}
            }

            if(isset($video_detail['programme']))
            {
                $titles = explode("\n\t",$video_detail['programme']);
                if(empty($titles[0]))
                {
                    $programme_title = $titles[1];
                }
                else if(empty($titles[1]))
                {
                    $programme_title = $titles[0];
                }
                else 
                {
                    $programme_title = $titles[0].' - '.$titles[1];
                }
            }

            //chapter list by video id
            $chapter_list = array();
            $chapter = new p_chapter();
            $vi_client = new VideoInfrastructureClient();
            $vi_data =  $vi_client->GetSource($video_detail['vi_id']);
            $vi_duration = empty($vi_data->duration) ? 0 : $vi_data->duration;
            $hour = floor($vi_duration / 3600);
            $hour = ($hour < 10) ? '0'.$hour  : $hour;

            $min = floor(( $vi_duration % 3600 ) / 60) ;
            $min = ($min < 10 )? '0'.$min : $min;

            $second =($vi_duration % 3600 ) % 60 ; 
            $second = ($second < 10 )? '0'.$second : $second;

            $init_chapter  = $hour.':'.$min.':'.$second;

            $this->setData("duration", $init_chapter);
            $chapter_list = $chapter->getChapterList($this->id);


            #casts:chapter
            $casts = array();
            if (!empty($chapter_list)) {
                foreach ($chapter_list as $chapter) {
                    if (!empty($chapter->casts) && substr($chapter->casts, 0, 1)!='[') {
                        $casts['chapter'][$chapter->id] = p_cast_dictionary::getCastListById(explode(',', $chapter->casts));
                    } else {
                        $casts['chapter'][$chapter->id] = array();
                    }
                }
            }

            $this->setData('casts', $casts);
            $this->setData("chapter_list", $chapter_list);

            //concurrent handle
            $concurrent_time = array();
            if (!empty($chapter_list))
            {
                foreach ($chapter_list as $chapter)
                {
                    $concurrent_time[] = $chapter->modified_at;
                }
            }
            $this->setData('concurrent_time', json_encode($concurrent_time));

            //delete chapters
            $this->setData('deleted_chapters', $this->deleted_chapters);

            // add publish log
            $publish_log = (!empty($chapter_list)) ? publish_log::getPublishLog('chapter', 
                $chapter_list[0]->id) : '';
            $this->setData("chapter_publishLog", $publish_log);
            

            //tvb category list
            if (!empty($chapter_list)) {
                $tvb_category_arr = array();
                foreach ($chapter_list as $chapter) {
                    $tvb_category_list = array();
                    $chapter_tvbcom_category = new p_chapter_tvbcom_category();
                    $tvb_category_list = $chapter_tvbcom_category->getCategoryByChapterID($chapter->id);
                    foreach($tvb_category_list as $tvb_category)
                    {
                        $parent_name = tvbcom_category::getParentName($tvb_category->system_label,
                            $tvb_category->parent_id);
                        $tvb_category_arr[$chapter->id][] = array("id"=>$tvb_category->category_id, 
                            "system_label"=>$parent_name." ".$tvb_category->system_label);
                    }
                   
                }
                $this->setData("tvb_category_list", $tvb_category_arr);
            }

		
            $tag_type = new tag_type();
            $allow_tag_list = $tag_type->findByInSql($chapter_allow_tag);
            $tag_arr = array();
            foreach ($allow_tag_list as $tag)
            {
                $tag_arr[$tag->id] = 
                    array("id"=>$tag->id,"name"=>$tag->system_label,'restrict'=>$tag->restricted);
            }
            $this->setData("chapter_allow_tag", $tag_arr);

            $this->setData("programme",$programme_title);
			$this->setData("tag_list", $all_tag_list);
			$this->setData("video", $video_detail);
			$this->setData("type", 'video');
			$this->setData("act", $this->act);
			$this->setData('from', $this->from);

			return  'succ';
		}
		catch(Exception $e)
		{
			error_log("video get: {$this->id}" . var_export($e,1));

			$this->emptyData();
			return 'system-error';
		}
	}

    private function __init_video_premium()
    {
        $p = new p_video_premium();
        return $p->get($this->id);
    }

    private function initCountry()
    {
        $country = new country();
        $this->setData('country', $country->getCountryList());
    }

    /*
    private function initVideoSubscription()
    {
        $video_subscription = new p_video_subscription;
        $subscription = $video_subscription->get($this->id);
        $subscription = Model::object2array($subscription);
        if (empty($subscription)) {
            $video_premium_flag = FALSE;
            $subscription = array(
                'country_allow_list'    => 'ALL', 
                'country_deny_list'     => '', 
                'publish_datetime'      => '0000-00-00 00:00:00', 
                'expire_datetime'       => '0000-00-00 00:00:00', 
                'free_flag'             => '0',
            );
        } else {
            $video_premium_flag = TRUE;
        }
        $this->initVideoSubscriptionStatus($video_premium_flag);
        $this->setData('video_subscription', $subscription);
    }
     */

    private function initVideoSubscriptionStatus($video_premium_flag)
    {
        if ($this->_programme_premium_flag) {
            $readonly = strtolower($this->act)=='edit' ? FALSE : TRUE;
            $show = TRUE;
        } else {
            $readonly = TRUE;
            $show = $video_premium_flag ? TRUE : FALSE;
        }

        $this->setData('video_subscription_readonly', $readonly);
        $this->setData('video_subscription_show', $show);
    }

    private function initProgrammePremiumFlag($programme_id)
    {
        if ($programme_id) {
            $programme = new p_programme;
            $result = $programme->get($programme_id);
            $this->setData('programme_premium_flag', $result->premium_flag);
        } 
    }

    private function __init_video_ppv()
    {
        $video_ppv = new p_video_ppv;
        $ppv = $video_ppv->get($this->id);
        $ppv = Model::object2array($ppv);
        if (empty($ppv)) {
            $ppv_ret = array(
                'publish_datetime'      => '0000-00-00 00:00:00', 
                'expire_datetime'       => '0000-00-00 00:00:00', 
                'ppv_country'=>'',
                'ppv_country_allow_deny'=> '',
            );
        }
        else 
        {
            if('ALL' == $ppv['country_allow_list'])
            {
                $deny_flag = 1; 
                $country = $ppv['country_deny_list'];
            }
            else
            {
                $deny_flag = 0;
                $country = $ppv['country_allow_list'];
            }

            $ppv_ret = array(
                'publish_datetime'      => $ppv['publish_datetime'], 
                'expire_datetime'       => $ppv['expire_datetime'], 
                'ppv_country'=> $country,
                'ppv_country_allow_deny'=> $deny_flag
            );
        }
        $this->setData('video_ppv', $ppv_ret);
    }
    private function __init_video_subscription()
    {
        $video_subscription = new p_video_subscription;
        $subscription = $video_subscription->get($this->id);
        $subscription = Model::object2array($subscription);
        if (empty($subscription)) 
        {
            $video_premium_flag = FALSE;
            $subscription_ret = array(
                'publish_datetime'      => '0000-00-00 00:00:00', 
                'expire_datetime'       => '0000-00-00 00:00:00', 
                'free'=>0,
                'subscription_country'=> '',
                'subscription_country_allow_deny'=> ''
            );
        }
        else 
        {
            $video_premium_flag = TRUE;
            if('ALL' == $subscription['country_allow_list'])
            {
                $deny_flag = 1; 
                $country = $subscription['country_deny_list'];
            }
            else
            {
                $deny_flag = 0;
                $country = $subscription['country_allow_list'];
            }
            $subscription_ret = array(
                'publish_datetime'      => $subscription['publish_datetime'], 
                'expire_datetime'       => $subscription['expire_datetime'], 
                'free'=>$subscription['free_flag'],
                'subscription_country'=> $country,
                'subscription_country_allow_deny'=> $deny_flag
            );
        }
        //$this->initVideoSubscriptionStatus($video_premium_flag);
        $this->setData('video_subscription', $subscription_ret);
    }
}
?>
